package com.spring.jwt.token.controller;

import com.spring.jwt.token.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/** 登录控制层
 * @author suncheng
 * @version 1.0
 * @description: TODO
 * @date 2025/5/30 10:45
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final JwtUtils jwtUtils;
    private final StringRedisTemplate redisTemplate;

    private final String REFRESH_TOKEN_PREFIX = "refresh_token:";

    @PostMapping("/login")
    public Map<String, String> login(@RequestBody Map<String, String> loginData) {
        String username = loginData.get("username");
        String password = loginData.get("password");

        if (!"admin".equals(username) || !"123456".equals(password)) {
            throw new RuntimeException("用户名或密码错误");
        }

        String accessToken = jwtUtils.generateAccessToken(username);
        String refreshToken = jwtUtils.generateRefreshToken(username);

        // 存储 refresh_token
        redisTemplate.opsForValue().set(REFRESH_TOKEN_PREFIX + username, refreshToken,
                Duration.ofSeconds(1800));

        Map<String, String> result = new HashMap<>();
        result.put("access_token", accessToken);
        result.put("refresh_token", refreshToken);
        result.put("expires_in", "300");

        return result;
    }

    @PostMapping("/refresh")
    public Map<String, String> refresh(@RequestBody Map<String, String> body) {
        String refreshToken = body.get("refresh_token");
        if (jwtUtils.isTokenExpired(refreshToken)) {
            throw new RuntimeException("Refresh Token 已过期");
        }

        String username = jwtUtils.getUsernameFromToken(refreshToken);

        // 验证 Redis 中是否存在 refresh_token
        String cachedToken = redisTemplate.opsForValue().get(REFRESH_TOKEN_PREFIX + username);
        if (cachedToken == null || !cachedToken.equals(refreshToken)) {
            throw new RuntimeException("非法 refresh_token");
        }

        // 生成新 access_token 和新的 refresh_token（可复用）
        String newAccessToken = jwtUtils.generateAccessToken(username);
        String newRefreshToken = jwtUtils.generateRefreshToken(username);

        redisTemplate.opsForValue().set(REFRESH_TOKEN_PREFIX + username, newRefreshToken,
                Duration.ofSeconds(1800));

        Map<String, String> result = new HashMap<>();
        result.put("access_token", newAccessToken);
        result.put("refresh_token", newRefreshToken);
        result.put("expires_in", "300");

        return result;
    }
}
